import { Component, Inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { MatSelectModule } from '@angular/material/select';

import { Dormitory } from '../../types/dormitory';

@Component({
  selector: 'app-dormitory-form',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    MatDialogModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonModule,
    MatSelectModule
  ],
  templateUrl: './dormitory-form.component.html',
  styleUrls: ['./dormitory-form.component.scss']
})
export class DormitoryFormComponent {
  form: FormGroup;

  constructor(
    private fb: FormBuilder,
    private dialogRef: MatDialogRef<DormitoryFormComponent>,
    @Inject(MAT_DIALOG_DATA) public data?: Dormitory
  ) {
    this.form = this.fb.group({
      room_number: [data?.room_number || '', [Validators.required]],
      building: [data?.building || '', [Validators.required]],
      floor: [data?.floor || '', [Validators.required, Validators.min(1)]],
      capacity: [data?.capacity || '', [Validators.required, Validators.min(1)]],
      occupied: [data?.occupied || 0, [Validators.required, Validators.min(0)]],
      status: [data?.status || '', [Validators.required]],
      description: [data?.description || '']
    }, { validators: this.occupiedValidator });
  }

  occupiedValidator(group: FormGroup) {
    const capacity = group.get('capacity')?.value;
    const occupied = group.get('occupied')?.value;
    
    if (capacity && occupied && occupied > capacity) {
      group.get('occupied')?.setErrors({ max: true });
    }
    return null;
  }

  onSubmit(): void {
    if (this.form.valid) {
      const dormitory: Dormitory = {
        ...this.form.value,
        id: this.data?.id
      };
      this.dialogRef.close(dormitory);
    }
  }

  onCancel(): void {
    // 清空表单
    this.form.reset();
    this.dialogRef.close();
  }
}